const centuries=document.getElementById('centuries');
const material=document.getElementById('material');
const article=document.getElementById('article');

var nowCentury,select={},gamePaused=false,lstSave=new Date().getTime();

function process(number=0)
{
    if(number === Infinity) return "Infinity";
    if(number<1e4) return number.toFixed(2);
    let digit=Math.floor(Math.log10(number));
    return (number/(10**digit)).toFixed(2)+"e"+digit;
};

function changeCentury(century)
{
    if(century==nowCentury) return;
    material.innerHTML="";
    for(let i in gamedata[century].material)
        if(gamedata[century].material[i].unlocked)
            material.innerHTML+=`
                <li class="list-group-item" name="${i}">
                    <div style="width:35%;display:inline-block">${gamedata[century].material[i].name}</div>
                    <div id="${i}-capacity" style="float:right"></div>
                </li>`;
    article.innerHTML="",nowCentury=century;
    if(select[nowCentury])
    {
        let temp=document.querySelector(`#material > li[name=${select[nowCentury]}]`);
        temp.className="list-group-item active",temp.setAttribute("aria-pressed","true"),changeArticle(select[nowCentury]);
    }
    return;
};

function changeArticle(mat)
{
    article.innerHTML="";
    let detail=gamedata[nowCentury].material[mat];
    article.innerHTML+=`<h4>${detail.name}</h4>`;
    article.innerHTML+=`<p class="hint">${detail.info}</p>`;
    article.innerHTML+=(detail.speed!==undefined? `<div class="speed">每秒生产 : ${process(detail.speed*25)} * <p style="color:#c5390d;display:inline-block">${process(detail.bounce)}</p> = <p style="color:#0667c8;display:inline-block">${process(detail.speed*detail.bounce*25)}</p></div>`:"");
    article.innerHTML+=`<hr>`;
    let option=detail.options;
    for(let item in option)
    {
        article.innerHTML+=`<div><h5>${option[item].title}</h5>\n<p class="hint">${option[item].info}</p>`,
        article.innerHTML+=(option[item].count!==undefined? `<p class="capacity">已有：${option[item].count}/${option[item].limit}</p>`:"");
        for(let it in option[item].buttons)
            article.innerHTML+=(option[item].buttons[it].cost.length? `<p class="require">要求：${eval(`let self=gamedata[nowCentury].material[select[nowCentury]].options[${item}];\`${option[item].buttons[it].cost}\``)}</p>`:""),
            article.innerHTML+=`<button type="button" class="btn btn-info btn-sm" ${eval(gamedata[nowCentury].material[select[nowCentury]].options[item].buttons[it].check)? "":"disabled"} name="option-${item}-${it}">${option[item].buttons[it].button}</button></div>`;
        article.innerHTML+="<hr>";
    }
    return;
}

function work()
{
    document.getElementById('trans-data').onclick=()=>{uploadData(processGamedata(gamedata));} // transfer data
    document.getElementById('fetch-data').onclick=()=>{ // fetch data
        gamePaused=true;
        $.confirm({
            title:"Are you sure?",content:"你的本地数据将被清空！",theme: 'supervan',
            buttons:{"YES":()=>{$.confirm({title:"Alert",content:"你将会使用你的服务器进度。",buttons:{"OK":()=>{fetchData()}}});},"NO":()=>{}},
        }); // use javacript-confirm
    }
    document.addEventListener('click',(event)=>{
        let target=event.target;
        if(target.parentNode&&target.parentNode.parentNode==material) target=target.parentNode;
        if(target.parentNode==material)
        {
            if(select[nowCentury]){let temp=document.querySelector(`#material > li[name=${select[nowCentury]}]`);temp.className="list-group-item",temp.setAttribute("aria-pressed","false");}
            select[nowCentury]=target.getAttribute("name"),target.className="list-group-item active",target.setAttribute("aria-pressed","true");
            changeArticle(target.getAttribute('name'));
            return;
        }
        if(target.parentNode==article&&target.tagName=="BUTTON")
        {
            let targetId=target.getAttribute('name').match(/^option-([0-9]+)-([0-9]+)$/);
            eval(gamedata[nowCentury].material[select[nowCentury]].options[targetId[1]].buttons[targetId[2]].onclick);
            changeArticle(select[nowCentury]);
        }
    }); // add event listener of clicking the buttons of increasing materials.
    window.setInterval(()=>{ // Main loop
        // Upload data to Server automatically.
        if(new Date().getTime()-lstSave>=30000) lstSave=new Date().getTime(),uploadData(processGamedata(gamedata));
        // game paused ?
        if(gamePaused) return; 
        // update the limit of every resources.
        let nowMaterials=material.children;
        for(let i of nowMaterials)
        {
            let temp=i.getAttribute('name');
            if(isNaN(gamedata[nowCentury].material[temp].count)) continue;
            document.getElementById(temp+'-capacity').innerHTML=
                process(gamedata[nowCentury].material[temp].count)+"/"+
                process(gamedata[nowCentury].material[temp].limit);
        }
        // update the status of each button.
        let id=0,temp;
        while((temp=document.getElementsByName(`option-${id}-0`)).length)
        {
            let pos=0;
            while((temp=document.getElementsByName(`option-${id}-${pos}`)).length)
            {
                let nowState=temp[0].getAttributeNames().join(' ').indexOf('disabled');
                if(nowState!=-1&&eval(gamedata[nowCentury].material[select[nowCentury]].options[id].buttons[pos].check))
                    temp[0].removeAttribute('disabled');
                else if(nowState==-1&&!eval(gamedata[nowCentury].material[select[nowCentury]].options[id].buttons[pos].check))
                    temp[0].setAttribute('disabled','');
                pos++;
            }
            id++;
        }
        // update count of every resources.
        for(let i in gamedata)
            for(let j in gamedata[i].material)
            {
                temp=gamedata[i].material[j];
                if(temp.speed!=undefined) temp.count=Math.min(temp.count+temp.speed*temp.bounce,temp.limit);
            }
        // unlock things that can be unlocked.
        // 1.century
        for(let i in gamedata)
        {
            if(gamedata[i].unlocked)
                document.getElementById(`century-${i}`).onclick=(e)=>{
                    if(nowCentury) document.getElementById(`century-${nowCentury}`).className="btn btn-secondary";
                    e.target.className="btn btn-secondary active";
                    changeCentury(e.target.getAttribute('name'));
                };
            if(!gamedata[i].unlocked&&eval(gamedata[i].unlock)===true)
                centuries.innerHTML+=`<button type="button" name="${i}" id="century-${i}" class="btn btn-secondary">${gamedata[i].title}</button>`,
                gamedata[i].unlocked=true;
        }
        // 2.materials and special pages
        for(let i0 in gamedata)
            for(let i in gamedata[i0].material)
                if(!gamedata[i0].material[i].unlocked&&eval(gamedata[i0].material[i].unlock)===true)
                {
                    gamedata[i0].material[i].unlocked=true,flushWebsite=true;
                    if(i0==nowCentury)
                        material.innerHTML+=`
                            <li class="list-group-item" name="${i}">
                                <div style="width:50%;display:inline-block">${gamedata[century].material[i].name}</div>
                                <div id="${i}-capacity" style="float:right"></div>
                            </li>`;
                }
    },1000/25);
}

(()=>{
    getSpinner();
    let spinnerHint=document.getElementById('spinner-hint');
    spinnerHint.innerHTML="Connecting server...";
    window.setTimeout(()=>{
        getData().then(async (data)=>{
            console.log("Fetch server data successfully.");
            gamedata=mergeData(JSON.parse(data),gamedata);
            centuries.innerHTML="";
            // Load server data.
            for(let i in gamedata)
                if(gamedata[i].unlocked)
                {
                    centuries.innerHTML+=`<button type="button" name="${i}" id="century-${i}" class="btn btn-secondary">${gamedata[i].title}</button>`;
                    document.getElementById(`century-${i}`).onclick=(e)=>{changeCentury(e.target.getAttribute('name'))};
                }
            $('#spinner-hint').fadeTo(500,0,"swing",()=>{
                spinnerHint.innerHTML="Connect successfully.";
                spinnerHint.style.color="green";
                $('#spinner-hint').fadeTo(500,1,"swing",()=>{
                    window.setTimeout(()=>{stopSpinner();work()},1000);
                });
            });
        },(xhr)=>{
            console.log("Fetch server data failed.");
            $('#spinner-hint').fadeTo(500,0,"swing",()=>{
                spinnerHint.innerHTML="Connect failed.";
                spinnerHint.style.color="red";
                $('#spinner-hint').fadeTo(500,1,"swing",()=>{
                    window.setTimeout(()=>{stopSpinner();work()},500);
                });
            });
        });
    },500);
})();